﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Designer.Event.UI;
using CPPEI.Coolzon.UI;
using CPPEI.Coolzon.UI.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// Interaction logic for NewTemplateWindow.xaml
    /// </summary>
    public partial class NewTemplateWindow : Window
    {
        private Designtime.Metadata.Template _template;
        private List<CPPEI.Coolzon.Metadata.PartLibItem> partLibItemList;
        private Coolzon.UI.Part newPart;
        private CPPEI.Coolzon.Designtime.Metadata.Part _dtPart;
        private bool _IsNewTemplate = false;
        private Designtime.Metadata.NodeBase DT_MetadataForRemoved = null;
        public NewTemplateWindow()
        {
            InitializeComponent();
            Title = "新建模板";
            UIContext.Current.IsEditTemplateMode = true;
        }
        public NewTemplateWindow(Designtime.Metadata.Template template, bool canEdit = true)
        {
            InitializeComponent();
            _template = template;
            Title = "编辑模板";
            UIContext.Current.IsEditTemplateMode = true;
            SetCanEdit(canEdit);
        }

        private void SetCanEdit(bool canEdit)
        {
            _ctlBtn.IsEnabled = canEdit;
            _ctlGrid.IsEnabled = canEdit;
            _temProperty.IsEnabled = canEdit;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitPartType();
            if (_template == null)
            {
                _name.Text = "新建模板" + (++UIContext.Current.CurrentSolution.IdSeed);
                _IsNewTemplate = true;
            }
            else
            {
                _name.Text = _template.Name;
                _dtPart = _template.Content;
                _IsNewTemplate = false;
                SetPartType(_template.Content.Type);
            }
        }

        private void SetPartType(string type)
        {
            Coolzon.Metadata.PartLibItem selected = partLibItemList.Find(a => string.Equals(a.Name, type));
            _partType.SelectedItem = selected;
        }

        private void InitPartType()
        {
            partLibItemList = new List<Coolzon.Metadata.PartLibItem>();
            Configuration.Client.PartLibsConfig partLibsConfig = Configuration.Client.Config.PartLibs;
            for (int partLibIndex = 0; partLibIndex < partLibsConfig.PartLibs.Count; partLibIndex++)
            {
                Configuration.Client.PartLib partlib = partLibsConfig.PartLibs[partLibIndex];
                if (string.Equals(partlib.Name, "SysPartLib"))
                {
                    continue;
                }
                string filePath = string.Format("{0}{1}{2}.xml", partLibsConfig.PartLibsBaseAddress, partLibsConfig.PartLibsDirectory, partlib.Name);

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(filePath);

                CPPEI.Coolzon.Metadata.PartLib partLib = Metadata.PartLibXmlProxy.Load(filePath);
                partLibItemList.AddRange(partLib.PartList);
            }
            _partType.ItemsSource = partLibItemList;
        }

        private void _partType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_partType.SelectedItem == null)
            {
                return;
            }
            _partpanel.Children.Clear();

            newPart = PartInstanceCache.GetPartInstance((CPPEI.Coolzon.Metadata.PartLibItem)_partType.SelectedItem);

            _partpanel.Children.Add(newPart);

            Guid areaId = Guid.NewGuid();
            if(_dtPart == null)
            {
                _dtPart = new Designtime.Metadata.Part(areaId,
                    ((CPPEI.Coolzon.Metadata.PartLibItem)_partType.SelectedItem).Name,
                    newPart.Name, newPart.Name);
            }
            else
            {
                _dtPart.RT_Part.Type = ((CPPEI.Coolzon.Metadata.PartLibItem)_partType.SelectedItem).Name;
            }

            // 设置元数据
            newPart.SetMetadata(_dtPart.RT_Part);
            DT_MetadataForRemoved = _dtPart;

            Coolzon.UI.XProperty.Converters.ConvertContext convertContext = new Coolzon.UI.XProperty.Converters.ConvertContext();
            convertContext.SolutionName = UIContext.Current.CurrentSolution.Name;
            convertContext.SolutionDirectory = UIContext.Current.LocalWorkSpace.LocalPath + UIContext.Current.CurrentSolution.ID + "\\";
            convertContext.SolutionFilePath = UIContext.Current.LocalWorkSpace.LocalPath + UIContext.Current.CurrentSolution.ID + "\\" + UIContext.Current.CurrentSolution.ID + ".xml";
            XPropertyUtility.LoadXPropertyValue(convertContext, newPart, _dtPart.RT_Part.Properties);
            newPart.Init(null);
            newPart.Active(null);

            _temProperty.SelectPartChanged(newPart);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_name.Text))
            {
                CustomMessageBox.ShowWarning("请输入名称");
                return;
            }
            if (_partType.SelectedItem == null)
            {
                CustomMessageBox.ShowWarning("请选择类型");
                return;
            }
            if (UIContext.Current.CurrentSolution.ExistTemplate(UIContext.Current.CurrentSelectedNode.Name, _name.Text))
            {
                CustomMessageBox.ShowError(string.Format("{0}模板名称已存在", _name.Text));
                return;
            }
            if (UIContext.Current.CurrentSelectedNode != null && UIContext.Current.CurrentSelectedNode.NodeStatus == NodeStatus.CheckOut)
            {
                CreateTemplate();
            }
            else
            {
                List<SolutionTreeViewNode> nodeList = new List<SolutionTreeViewNode>();
                nodeList.Add(UIContext.Current.CurrentSelectedNode);
                CheckOutThread.Start(nodeList, ReportProgress, Completed);
                ProgressbarWindow.Instance.ShowProgress(false);
            }
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
        public void ReportProgress(Guid id, string name, int current, int total)
        {
            Dispatcher.Invoke(() =>
            {
                ProgressbarWindow.Instance.ReportProgress(current, total);
            });
        }

        public void Completed(bool HasError, int successed, int total)
        {
            ProgressbarWindow.Instance.Complete();
            if (HasError)
            {
                this.Dispatcher.Invoke(() =>
                {
                    CustomMessageBox.ShowError("方案签出失败");
                });
                return;
            }
            CreateTemplate();
        }
        private void CreateTemplate()
        {
            if (_IsNewTemplate)
            {
                this.Dispatcher.Invoke(() =>
                {
                    //_dtPart.RT_Part = (Metadata.Part)newPart.Metadata;
                    UIEventBus.Publish(new UICreateTemplate(_name.Text, _dtPart));
                    Logger.DebugToTag(Library.LogTAG, string.Format("name:{0},type:{1}", _name.Text, _partType.SelectedItem));
                    this.DialogResult = true;
                });
            }
            else
            {
                this.Dispatcher.Invoke(() =>
                {
                    //_dtPart.RT_Part = (Metadata.Part)newPart.Metadata;
                    UIEventBus.Publish(new UIUpdateTemplate(_template.SceneID, _template.ID, _name.Text, _dtPart));
                    Logger.DebugToTag(Library.LogTAG, string.Format("name:{0},type:{1}", _name.Text, _partType.SelectedItem));
                    this.DialogResult = true;
                });
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            UIContext.Current.IsEditTemplateMode = false;
        }
    }
}
